package com.google.product.controller;

import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.google.product.entity.GoodsEntity;
import com.google.product.entity.ProductEntity;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import com.google.product.service.GoodsService;
import com.google.product.utils.PageUtils;
import com.google.product.utils.R;



/**
 * 商品管理
 *
 * @author name
 * @email email@gmail.com
 * @date 2020-12-06 17:46:17
 */
@RestController
@RequestMapping("generator/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    RestHighLevelClient client;//测试es官方客户端
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("esSearch")
    public R esSearch(String key,String pageFrom,String pageSize) throws IOException {
        System.out.println(key);
        System.out.println(pageFrom);
        System.out.println(pageSize);
        String[] split = key.split("");

        String newKey = "*";

        for(String s :split){
            newKey = newKey+s+"*";
        }
        //1. 创建检索请求
        SearchRequest searchRequest = new SearchRequest();

        //1.1）指定索引
        searchRequest.indices("store");
        //1.2）构造检索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.wildcardQuery("name",newKey));
//        sourceBuilder.query(QueryBuilders.matchQuery("info","info3").operator(Operator.OR));//精确查询
//        sourceBuilder.query(QueryBuilders.matchQuery("img","img2"));//精确查询

//        sourceBuilder.query(QueryBuilders.termQuery("info","info1"));//term精确
//        sourceBuilder.query(QueryBuilders.matchAllQuery());//查全部
        sourceBuilder.from(0); //从第几个开始
        sourceBuilder.size(50);


        System.out.println("检索条件："+sourceBuilder);
        searchRequest.source(sourceBuilder);
        //2. 执行检索
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("检索结果："+searchResponse);

        //3. 将检索结果封装为Bean
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();

        Long l = hits.getTotalHits().value;//总记录数

        ArrayList<GoodsEntity> list = new ArrayList<>();

        for (SearchHit searchHit : searchHits) {

            String sourceAsString = searchHit.getSourceAsString();

            GoodsEntity goodsEntity = JSON.parseObject(sourceAsString, GoodsEntity.class);
            goodsEntity.setGoodsId(Long.valueOf(searchHit.getId()));
            System.out.println(goodsEntity);
            list.add(goodsEntity);

        }

        PageUtils pageUtils = new PageUtils();
        pageUtils.setPageSize(10);
        pageUtils.setCurrPage(1);
        pageUtils.setTotalCount(l.intValue());
        pageUtils.setList(list);

        return R.ok().put("page", pageUtils);
    }
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:goods:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = goodsService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{goodsId}")
    @RequiresPermissions("generator:goods:info")
    public R info(@PathVariable("goodsId") Long goodsId){
		GoodsEntity goods = goodsService.getById(goodsId);

        return R.ok().put("goods", goods);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
//    @RequiresPermissions("generator:goods:save")
    public R save(@RequestBody GoodsEntity goods){
//		goodsService.save(goods);
        rabbitTemplate.convertAndSend("goods-exchange","goods.save.mysql",goods);
        rabbitTemplate.convertAndSend("goods-exchange","goods.save.es",goods);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("generator:goods:update")
    public R update(@RequestBody GoodsEntity goods){
//		goodsService.updateById(goods);
        rabbitTemplate.convertAndSend("goods-exchange","goods.update.mysql",goods);
        rabbitTemplate.convertAndSend("goods-exchange","goods.update.es",goods);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("generator:goods:delete")
    public R delete(@RequestBody Long[] goodsIds){
//		goodsService.removeByIds(Arrays.asList(goodsIds));
        rabbitTemplate.convertAndSend("goods-exchange","goods.delete.mysql",goodsIds);
        rabbitTemplate.convertAndSend("goods-exchange","goods.delete.es",goodsIds);
        return R.ok();
    }

    //添加到购物车
    @PostMapping("saveCart")
    public R saveCart(@RequestBody GoodsEntity goodsEntity){
        redisTemplate.opsForValue().set("cart:"+goodsEntity.getGoodsId()+"",goodsEntity);
        return R.ok();
    }

    //获取购物车信息
    @PostMapping("getCart")
    List<GoodsEntity> getCart(){
        Set<String> keys = redisTemplate.keys("cart:*");
        ArrayList<String> listKeys = new ArrayList<>(keys);
        Collections.sort(listKeys);
        List<GoodsEntity> list = redisTemplate.opsForValue().multiGet(listKeys);
        return list;
    }

}
